<?php
namespace app\mall\controller;
use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use app\mall\model\Store as StoreModel;
use think\Db;
use think\Request;
use pinyin\Pinyin;

/**
 * 系统权限管理控制器
 * Class Auth
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 18:13
 */
class Mall extends BasicAdmin
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'Store';
    /*************************门店分区************************************************************************/
    /**
     * 用户列表
     */
    public function store()
    {
        $this->title = '门店列表';

        $get = $this->request->get();
        $db = Db::name($this->table)->alias('a')->where(['a.is_deleted'=>0]);
        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.title', "%{$get[$key]}%");
        }
        //城市列表
        $city = Db::name('city')->select();

        $nodes = session('user.nodes');
        $reg = "/^store\/[abcdefghihklmnopqrstuvwxyz_ABCDEFGHIGKLMNOPQRSTUVWXYZ]{0,100}\//is";
        foreach($nodes as $k => $v){        //取出最顶部的门店链接
            if(!preg_match($reg, $v)){
                unset($nodes[$k]);
            }
        }


        $s_url = db('system_menu')->where('url','in',$nodes)->order('sort desc')->limit(1)->value('url');        //查询出门店跳转的链接
        $this->assign('city',$city);
        $this->assign('root',request()->domain());               //网站根目录
        $yangshi = config("qiniu");
        $this->assign('yangshi',$yangshi['yangshi']);            //七牛样式后缀
        $this->assign('s_url',$s_url);                           //门店跳转url

        return parent::_list($db);
    }
    /**
     * 用户添加
     */
    public function add_store()
    {
        if($this->request->isPost()){
            $post = input('post.');
            if($post['city_key'] == ''){
                $this->error('请选择城市','');
            }
            $city = db('city')->where('key',$post['city_key'])->find();        //城市门店
            $data = array('title'=>$post['title'],'address'=>$post['address'],'city_key'=>$city['key'],'city_code'=>$city['code'],'price_status'=>$post['price_status'],'mobile'=>$post['mobile'],'dada'=>$post['dada'],'business_time_start'=>$post['business_time_start'],'business_time_end'=>$post['business_time_end'],'is_jiameng'=>$post['is_jiameng']);
//            $address = $post['address'];
//            //腾讯地图地址API
//            $url='http://apis.map.qq.com/ws/geocoder/v1/?address='.$post["address"].'&key=SCIBZ-DHYCX-RQZ4A-ZZB2V-2VHPH-N4FUM';
//            if($result=file_get_contents($url)){
//                $result = json_decode($result,true);
////                halt($result);
//                if($result['status'] == 0){
//                    //输入地址错误
//                    if($result['result']['title'] == $result['result']['address_components']['district']){
//                        $this->error('输入地址有误,请重新填写','');
//                    }else{      //输入地址正确
//                        $data['lng'] = $result['result']['location']['lng'];
//                        $data['lat'] = $result['result']['location']['lat'];
//                    }
//                }else{
//                    $this->error('地址输入错误，请重试！');
//                }
//            }
            $StoreModel = new StoreModel();

            $result = $StoreModel->add($data);
            $result['code']==1?$this->success('保存成功',url('@admin').'#'.url('Mall/store').'?spm='.input('spm')):$this->error($result['msg'],'');
        }
        //城市列表
        $city = Db::name('city')->select();
        $this->assign('city',$city);
        return $this->_form($this->table, 'add_store');
    }
    /**
     * 用户编辑
     */
    public function edit_store()
    {
        $id = input('id');
        if($this->request->isPost()){
            $post = input('post.');     //收到的数据
            if($post['city_key'] == ''){
                $this->error('请选择城市','');
            }
//            //腾讯地图地址API
//            $url='http://apis.map.qq.com/ws/geocoder/v1/?address='.$post["address"].'&key=SCIBZ-DHYCX-RQZ4A-ZZB2V-2VHPH-N4FUM';
//            if($result=file_get_contents($url)){
//                $result = json_decode($result,true);
//                if($result['status'] == 0){
//                    //输入地址错误
//                    if($result['result']['title'] == $result['result']['address_components']['district']){
//                        $this->error('输入地址有误,请重新填写','');
//                    }else{      //输入地址正确
//                        $data['lng'] = $result['result']['location']['lng'];
//                        $data['lat'] = $result['result']['location']['lat'];
//                    }
//                }else{
//                    $this->error('地址输入错误，请重试！');
//                }
//            }
            $city = db('city')->where('key',$post['city_key'])->find();        //城市门店
            $data = array('title'=>$post['title'],'city_code'=>$city['code'],'city_key'=>$post['city_key'],'address'=>$post['address'],'price_status'=>$post['price_status'],'mobile'=>$post['mobile'],'dada'=>$post['dada'],'business_time_start'=>$post['business_time_start'],'business_time_end'=>$post['business_time_end'],'is_jiameng'=>$post['is_jiameng']);

            $StoreModel = new StoreModel();     //门店id
            $result = $StoreModel->edit($data,$post['id']);
            $result['code'] == 1?$this->success('保存成功',url('@admin').'#'.url('Mall/store').'?spm='.input('spm')):$this->error($result['msg'],'');
        }
        $vo = Db::name('store')->where('id',$id)->find();       //查新门店
        $this->assign('vo',$vo);
        //城市列表
        $city = Db::name('city')->select();
        $this->assign('city',$city);
        return $this->fetch('edit_store');
    }
    /**
     * 门店禁用
     * @return [type] [description]
     */
    public function store_forbid(){
        $id = input('id');
        $res = Db::name('store')->where('id',$id)->update(['id'=>$id,'status'=>0]);
        $res>0?$this->success('门店关闭成功',""):$this->error("门店关闭失败，请稍候再试！");
    }
    /**
     * 门店启用
     * @return [type] [description]
     */
    public function store_start(){
        $id = input('id');
        $res = Db::name('store')->where('id',$id)->update(['id'=>$id,'status'=>1]);
        $res>0?$this->success('门店开启成功',""):$this->error("门店开启失败，请稍候再试！");
    }
    /**
     * 删除门店
     * @return [type] [description]
     */
    public function del_store(){
        $id = input('id');
        $res = Db::name('store_goods')->where('store_id',$id)->count();
        if($res>0) $this->error('该门店已分配商品，不能删除');
        $res = Db::name('store')->where('id',$id)->delete();
        $res>0?$this->success('删除成功',''):$this->errro('删除失败','');
    }
    /*************************门店分区************************************************************************/

    /************************分配店长**********************************************************************/
    /**
     * 分配门店店长
     */
    public function add_manager(){
        if(request()->isPost()){
            $post = input('post.');
            if(!empty($post['id'])){        //修改
                if(!empty($post['password'])){
                    $post['repassword']!=$post['password']?$this->error('两次密码填写不一致',''):'';
                    $password = md5($post['password']);
                    $data = array('store_id'=>$post['store_id'],'password'=>$password,'is_manager'=>1,'status'=>1);
                    $result = Db::name('system_user')->where('id',$post['id'])->update($data);
                    $result!==false?$this->success('保存成功',''):$this->error('保存失败','');
                }
                $this->success('保存成功','');
            }else{
                $admin = Db::name('system_user')->where('username',$post['username'])->find();
                if(!empty($admin)) $this->error('登录名已被占用','');
                $post['repassword']!=$post['password']?$this->error('两次密码填写不一致',''):'';
                $password = md5($post['password']);
                $data = array('store_id'=>$post['store_id'],'username'=>$post['username'],'password'=>$password,'is_manager'=>1,'status'=>1);
                $result = Db::name('system_user')->insert($data);
                $result>0?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }
        $id = input('id');          //门店id
        $map['store_id'] = array('eq',$id);     //门店id
        $map['is_manager'] = array('eq',1);     //是否是管理员
        $vo = Db::name('system_user')->where($map)->find();
        $this->assign('vo',$vo);
        if(!empty($vo)){
            $this->assign('pass','留空为不修改密码');
            $this->assign('repass','留空为不修改密码');
        }
        $this->assign('store_id',$id);            //门店id
        return $this->fetch('add_manager');
    }
    /************************分配店长**********************************************************************/

    /************************一键登入门店**********************************************************************/
    /**
     * @Author lignyun
     * @Desc    一键登入门店
     */
    public function loginStore(){
        $store_id = input('id');        //门店id
        session('user.store_id',$store_id);     //一键管理门店
//        header('Location:http://yunshangbalei.com/index.php/admin.html#/index.php/store/index/edit.html?spm=m-108-110');
        $this->redirect(url('@store/index/edit'));
    }
    /************************一键登入门店**********************************************************************/

    /************************门店所属城市**********************************************************************/
    /**
     * @Author lignyun
     * @Desc    门店所属城市
     */
    public function city(){
        $this->title = '城市列表';
        $table = "City";
        $get = $this->request->get();
        $db = Db::name($table)->alias('a')->join('ys_store b','a.store_id=b.id','LEFT')->where('a.is_deleted',0)->field('a.*,b.title');
        foreach (['value'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.value', "%{$get[$key]}%");
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('a.value', "%{$get[$key]}%");
        }
        return parent::_list($db);
    }

    /**
     * @Author lignyun
     * @Desc    添加城市
     */
    public function add_edit_city(){
        if(request()->isPost()){
            $post = input('post.');
            $pinyin = new Pinyin();
            $post['key'] = $pinyin->getAllPY($post['value']);
            //新增
            if(empty($post['id'])){
                //添加时间
                $post['addtime'] = time();
                $res = Db::name('city')->insert($post);
                $res>0?$this->success('保存成功',''):$this->error('保存失败','');
            }else{
                $res = Db::name('city')->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }else{
            $id = input('id');
            $info = Db::name('city')->where('id',$id)->find();
            $this->assign('info',$info);
            return $this->fetch('add_edit_city');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    门店余额明细
     * 2018-05-18
     */
    public function store_credit_log(){
        $this->title = '余额明细';
        $table = "stre_credit_log";
        $get = $this->request->get();
        $id = input('id');

        $db = db('store_credit_log')->alias('a')->join('ys_system_user b','a.admin_id=b.id','LEFT')->where('a.store_id',$id)->order('a.id desc')->field('a.*,b.username');
        if(isset($get['date']) && $get['date'] !== '') {
            // list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            list($start, $end) = explode(' - ', $get['date']);
            $start = $start."  00:00:00";		$end = $end." 23:59:59";
            $start = strtotime($start);			$end = strtotime($end);
            $db->whereBetween('a.addtime',["{$start}", "{$end}"]);
        }

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    门店打款
     * 2018-05-18
     */
    public function deal_store_credit(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $store = db('store')->where('id',$post['id'])->find();
            $data_log = [
                'store_id'=>$post['id'],
                'order_id'=>0,
                'type'=>2,
                'credit'=>$post['credit'],
                'cur_credit'=>$store['credit'] - $post['credit'],
                'admin_id'=>session('user.id'),
                'remark'=>'后台打款'.$post['credit'],
                'addtime'=>time(),
                'order_sn'=>''
            ];
            db('store_credit_log')->insert($data_log);
            $res = db('store')->where('id',$post['id'])->setDec('user_money',$post['credit']);
            $res!==false?$this->success('余额扣除成功，请及时线下打款',''):$this->error('打款失败,请稍后再试','');
        }else{
            $id = input('id');
            $store = db('store')->where('id',$id)->find();
            $this->assign('store',$store);

            return $this->fetch();
        }
    }

        /**
     * @Author lignyun
     * @Desc    删除门店
     */
    public function del_city(){
        $table = 'City';
        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /**
     * @Author  lingyun
     * @Desc    设置推荐的门店
     */
    public function set_recommend_store(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $res = db('city')->where('key',$post['key'])->update(['store_id'=>$post['store_id']]);
            $res!==false?$this->success('设置成功',''):$this->error('设置失败','');
        }else{
            $city_key = input('key');      //门店的key
            $where = [
                'city_key'=>$city_key,
                'is_deleted'=>0,
                'status'=>1
            ];
            //门店列表
            $list = db('store')->where($where)->field('id,title,logo')->select();
            $city = db('city')->where('key',$city_key)->find();

            $this->assign('list',$list);
            $this->assign('city',$city);
            $this->assign('city_key',$city_key);
            return $this->fetch('set_recommend_store');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    一键登录门店
     * 2018-05-04
     */
    public function login_store(){
        $storeid = input('storeid');
        if(!empty($storeid)){           //门店id
            session('user.store_id',$storeid);
        }
        $root = request()->domain();
        $nodes = session('user.nodes');
        $reg = "/^store\/[abcdefghihklmnopqrstuvwxyz_ABCDEFGHIGKLMNOPQRSTUVWXYZ]{0,100}\//is";
        foreach($nodes as $k => $v){        //取出最顶部的门店链接
            if(!preg_match($reg, $v)){
                unset($nodes[$k]);
            }
        }
        //http://ysbl.fxshe.com/index.php/admin#/index.php/mall/mall/store.html?spm=m-103-105
        $s_url = db('system_menu')->where('url','in',$nodes)->order('sort desc')->limit(1)->value('url');        //查询出门店跳转的链接
//        halt($root.'/index.php/admin.html#/index.php/'.$s_url.'.html?storeid='.$storeid);
        $this->redirect($root.'/index.php/admin.html#/index.php/'.$s_url.'.html?storeid='.$storeid);
    }



}